<script setup>
import SmtHeader from '@/layout/SmtHeader.vue';
import SmtFooter from '@/layout/SmtFooter.vue';
import { useRouter, useRoute } from 'vue-router';
import { reactive, ref, computed, onMounted } from 'vue';
import RobotCertification from '@/components/robotCertification/RobotCertification.vue';
import { validateEmail } from '@/utils/formValidation.js';
import { login, querySocialAuthRedirect, SocialAccountAuthorization } from '@/server/api/auth.js';
import icon_google from '/src/assets/images/login/icon_google_circle@2x.png';
import icon_facebook_circle from '/src/assets/images/login/icon_facebook_circle@2x.png';
import icon_twitter_circle from '/src/assets/images/login/icon_twitter_circle@2x.png';
import icon_in_circle from '/src/assets/images/login/icon_in_circle@2x.png';
import ForgetPassword from './ForgetPassword.vue';
import { useI18n } from 'vue-i18n';
const { t } = useI18n();

const loginFormRef = ref();
const loginForm = reactive({
  username: '',
  password: '',
  captcha: [],
});
const thirdPartyType = ref('');
const mailVisible = ref(false);

const isRobotCertification = computed(() => {
  return loginForm.captcha.length === 0;
});

const router = useRouter();
const route = useRoute();
const otherLoginList = [
  {
    icon: icon_google,
    type: '1',
  },
  {
    icon: icon_facebook_circle,
    type: '2',
  },
  {
    icon: icon_twitter_circle,
    type: '3',
  },
  {
    icon: icon_in_circle,
    type: '4',
  },
];

const rules = {
  username: [
    { required: true, message: t('mall.enter_account_number'), trigger: 'blur' },
    { validator: validateEmail, trigger: 'blur' },
  ],
  password: [
    { required: true, message: t('mall.enter_password'), trigger: 'blur' },
    { min: 6, message: t('mall.enter_password', { num: 6 }), trigger: 'blur' },
  ],
};

/**
 * 表单校验
 * @param {*} formEl
 */
const handleLogin = async (formEl) => {
  console.log('formEl', formEl);
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      loginSubmit();
    } else {
      console.log('error submit!', fields);
    }
  });
};

/**
 * 登录
 */
const loginSubmit = () => {
  const obj = {
    client_id: import.meta.env.VITE_APP_CLIENT_ID,
    client_secret: import.meta.env.VITE_APP_CLIENT_SECRET,
    grant_type: 'password',
    login_type: 1,
    password: loginForm.password,
    // password: '123456789',
    scope: 'all',
    source: 1,
    // username: '123456@qq.com',
    username: loginForm.username,
  };
  login(obj).then((res) => {
    if (res.code === 200) {
      window.localStorage.setItem('loginIfo', JSON.stringify(res.data));
      router.push({ path: '/' });
    }
  });
};

const goRegister = () => {
  router.push({ path: '/register' });
};

const changeRobotCertification = (value) => {
  loginForm.captcha[0] = value;
};

/**
 * 快捷登录选项
 * @param {*} type
 */
const getSocialAuthRedirect = (type) => {
  localStorage.setItem('loginType', type);
  if (type === '1') {
    // thirdPartyType.value = type;
    // const currentPath = 'http://smtshop.hwur.com';
    // 获取当前域名地址
    const protocol = window.location.protocol;
    const host = window.location.host;
    // const currentPath = 'http://oa.test.hwur.com:8000/';
    const currentPath = protocol + '//' + host;
    const obj = {
      type: type,
      redirectUri: currentPath,
    };
    querySocialAuthRedirect(obj).then((res) => {
      if (res.code === 200) {
        window.location.href = res.data;
      }
    });
  }
};

/**
 * 忘记密码
 */
const forgetPassword = () => {
  mailVisible.value = true;
};

const closeMailVisible = () => {
  mailVisible.value = false;
};
onMounted(() => {
  const { email } = route.query;
  loginForm.username = email;
});
</script>
<template>
  <smt-header></smt-header>
  <div class="login">
    <div class="login-container">
      <!-- 登录容器 -->
      <div class="login-box">
        <h2 class="login-box-title">{{ $t('mall.member_login') }}</h2>
        <el-form
          ref="loginFormRef"
          class="login-form"
          :model="loginForm"
          :rules="rules"
          hide-required-asterisk
        >
          <el-form-item prop="username">
            <el-input
              class="w-304"
              v-model="loginForm.username"
              autocomplete="off"
              :placeholder="$t('mall.enter_login_email_or_username')"
            />
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              class="w-304"
              v-model="loginForm.password"
              type="password"
              autocomplete="off"
              :placeholder="$t('mall.enter_password')"
            />
          </el-form-item>
          <el-form-item label-width="0" prop="captcha">
            <el-checkbox-group v-model="loginForm.captcha">
              <RobotCertification
                name="captcha"
                @changeRobotCertification="changeRobotCertification"
              />
            </el-checkbox-group>
          </el-form-item>
        </el-form>
        <el-button
          class="login-btn"
          type="primary"
          :disabled="isRobotCertification"
          @click="handleLogin(loginFormRef)"
          >{{ $t('om.Login') }}</el-button
        >
        <div class="forget">
          <p @click="forgetPassword">{{ $t('om.Forgotyourpassword') }}</p>
        </div>
      </div>
      <div class="other-login">
        <div class="other-login-box">
          <img
            :src="item.icon"
            v-for="(item, index) in otherLoginList"
            :key="index"
            @click="getSocialAuthRedirect(item.type)"
          />
        </div>
      </div>
      <p class="login-tips">
        {{ $t('om.Notamember') }}<a class="link" @click="goRegister">{{ $t('om.SignUpNow') }}</a>
      </p>
    </div>
  </div>

  <!-- 底部 -->
  <smt-footer></smt-footer>

  <ForgetPassword
    v-model="mailVisible"
    :title="$t('om.Retrievepassword')"
    @closeMailVisible="closeMailVisible"
  />
</template>

<style lang="scss" scoped>
.w-304 {
  width: 303px;
}
.login {
  box-sizing: border-box;
  padding-top: 80px;
  height: 700px;
  background: url('@/assets/images/login/bg_login@2x.png') no-repeat;
  background-size: cover;
  .link {
    cursor: pointer;
  }
  &-container {
    margin: 0 auto;
    width: 382px;
    .login-box {
      box-sizing: border-box;
      padding: 24px 36px;
      // height: 328px;
      border-radius: 28px;
      background: #ffffff4d;
      &-title {
        padding-bottom: 24px;
        text-align: center;
        color: #5255fe;
        font-size: 20px;
        font-weight: 700;
        color: var(--mall-color-primary);
      }

      .login-form {
        .el-input {
          --el-input-height: 45px;
        }

        .el-form-item {
          margin-bottom: 20px;
        }

        .captcha-box {
          box-sizing: border-box;
          width: 100%;
          padding: 0px 12px;
          border-radius: 8px;
          border: 1px solid #ffffff;
          background: #ffffff66;
        }
      }

      .login-btn {
        margin-top: 4px;
        width: 303px;
        height: 52px;
      }
    }

    .other-login {
      &-box {
        display: flex;
        justify-content: space-between;
        padding: 24px 52px 0;

        > img {
          &:not(&:first-child) {
            filter: grayscale(1);
            cursor: default;
          }
          cursor: pointer;
          width: 40px;
        }
      }
    }

    .login-tips {
      padding-top: 24px;
      text-align: center;
      color: #fff;
      font-size: 16px;
      > a {
        display: inline-block;
        color: var(--mall-color-primary);
        text-decoration: underline;
      }
    }
    .forget {
      width: 100%;
      height: 30px;
      color: var(--mall-color-primary);
      font-size: 14px;
      p {
        padding: 8px 0;
        cursor: pointer;
        float: right;
      }
    }
  }
}
</style>
